<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\api\model\order\Order as OrderModel;
use app\api\model\order\OrderMaster as OrderMasterModel;
use app\api\model\hospital\Hospital as HospitalModel;
use think\Db;

/**
 * 订单接口
 */
class OrderSale extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->loadlang('order');
    }

    /**
     * 待办列表
     */
    public function todoList()
    {
        $hospitalList = HospitalModel::where('user_id', $this->auth->id)->select();
        foreach ($hospitalList as &$value) {
            $value['status10'] = OrderMasterModel::where('hospital_id', $value['id'])->where('status', 10)->where('sole_id', $this->auth->id)->count('id');
            $value['status20'] = OrderMasterModel::where('hospital_id', $value['id'])->where('status', 20)->where('sole_id', $this->auth->id)->count('id');
            $value['status30'] = OrderMasterModel::where('hospital_id', $value['id'])->where('status', 30)->where('sole_id', $this->auth->id)->count('id');
            $value['total'] = $value['status10'] + $value['status20'] + $value['status30'];
            $value['orderUpdateTime'] = OrderMasterModel::where('hospital_id', $value['id'])->where('status', 'in', [10, 20])->where('sole_id', $this->auth->id)->order('updatetime desc')->value('updatetime') ?? 0;
        }
        usort($hospitalList, function ($a, $b) {
            return $b['orderUpdateTime'] - $a['orderUpdateTime'];
        });
        $this->success('', $hospitalList);
    }

    public function todoDetail(){
        $hospital_id = $this->request->post('hospital_id');
        if (!$hospital_id) {
            $this->error("参数错误");
        }
        $hospital = HospitalModel::find($hospital_id);
        $status10 = OrderMasterModel::where('hospital_id', $hospital_id)->where('status', 10)->where('sole_id', $this->auth->id)->count('id');
        $status20 = OrderMasterModel::where('hospital_id', $hospital_id)->where('status', 20)->where('sole_id', $this->auth->id)->count('id');
        $status30 = OrderMasterModel::where('hospital_id', $hospital_id)->where('status', 30)->where('sole_id', $this->auth->id)->count('id');

        $this->success('', [
            'status10' => $status10,
            'status20' => $status20,
            'status30' => $status30,
            'hospital' => $hospital,
        ]);
    }


    /**
     * 订单列表
     */
    public function orderList()
    {
        $hospital_id = $this->request->post('hospital_id');
        $title = $this->request->post('title');
        $status = $this->request->post('status');
        $between = $this->request->post('between/a');
        $page = $this->request->post('page', 1);
        $limit = $this->request->post('limit', 10);

        $where = ['sole_id' => $this->auth->id];
        if ($status) {
            $where['status'] = $status;
            if($status==30){
                // 已送检
                $where['status'] = 30;
                $where['report_status'] = 10;
            }else if($status==40){
                // 检测中
                $where['status'] = 30;
                $where['report_status'] = 20;
            }else if($status==50){
                // 检测部分完成
                $where['status'] = 30;
                $where['report_status'] = 25;
            }else if($status==60){
                // 检测完成
                $where['status'] = 30;
                $where['report_status'] = 30;
            }
        } else {
            $where['status'] = ['in', [10, 20, 30, -10, -20]];
        }
        if ($hospital_id) {
            $where['order.hospital_id'] = $hospital_id;
        }
        if ($between && count($between) == 2) {
            $where['order.createtime'] = ['between', [strtotime($between[0] . ' 00:00:00'), strtotime($between[1] . ' 23:59:59')]];
        }
        if($title){
            $where['order.username'] = ['like', '%'.$title.'%'];
        }


        $data = OrderMasterModel::alias('order')->field("order.*")
                        ->where($where)
                        ->with(['ordergoods', 'orderTube','hospital'])
                        ->order("order.createtime asc")
                        ->paginate($limit, false, ['page' => $page]);
        $this->success('', $data);
    }

    /**
     * 订单详情
     */
    public function orderDetail()
    {
        $id = $this->request->get('id');
        if (!$id) {
            $this->error("参数错误");
        }
        $order = OrderMasterModel::with(['ordergoods','orderReport','orderTube'])->find($id);
        if (!$order) {
            $this->error("订单不存在");
        }
        if ($order->sole_id != $this->auth->id) {
            $this->error("没有权限查看此订单");
        }
        // $orderTube = \app\api\model\order\OrderTube::with(['biaobenRongqi'])->where('id',$id)->select();
        // $order['order_tube'] = $orderTube;
        $this->success('', $order);
    }

    /**
     * 取消订单
     */
    public function cancelOrder()
    {
        $id = $this->request->post('id');
        $goods_ids = $this->request->post('goods_ids/a',[]);
        if (!$id || count($goods_ids) == 0) {
            $this->error("参数错误");
        }
        $order = OrderMasterModel::find($id);
        if (!$order) {
            $this->error("订单不存在");
        }
        if ($order->sole_id != $this->auth->id) {
            $this->error("没有权限查看此订单");
        }
        if ($order->status == 0 || $order->status == -10 || $order->status == -20 || ($order->status == 30 && $order->report_status == 30)) {
            $this->error("该状态不可取消订单");
        }

        $goodsList = \app\api\model\order\OrderGoods::where('order_master_id', $id)->where('id', 'in', $goods_ids)->select();
        if (count($goodsList) != count($goods_ids)) {
            $this->error("参数错误");
        }
        $goodsListAll = \app\api\model\order\OrderGoods::where('order_master_id', $id)->select();
        $goodsCount = count($goodsListAll);

        $rongqiIds = [];
        $rongqiIds2 = [];
        $model = new \app\api\model\order\Order();
        foreach ($goodsList as $goods) {
            $rongqi = $model->getRongqiList($goods);
            foreach ($rongqi as $rongqi_item) {
                $item = $rongqi_item->toArray();
                if($index = array_search($rongqi_item->id,$rongqiIds2) === false){
                    $rongqiIds2[] = $rongqi_item->id;
                }
            }
        }

        foreach ($goodsListAll as $goods) {
            if(array_search($goods->id,$goods_ids) !== false){
                continue;
            }
            $rongqi = $model->getRongqiList($goods);
            foreach ($rongqi as $rongqi_item) {
                $item = $rongqi_item->toArray();
                if($index = array_search($rongqi_item->id,$rongqiIds) === false){
                    $rongqiIds[] = $rongqi_item->id;
                }
            }
        }

        $rongqiDelete = [];
        foreach ($rongqiIds2 as $rongqi_id) {
            if(array_search($rongqi_id,$rongqiIds) === false){
                $rongqiDelete[] = $rongqi_id;
            }
        }

        

        DB::startTrans();
        try {
            if(count($rongqiDelete) > 0){
                $res = \app\api\model\order\OrderTube::where('biaoben_rongqi_id','in', $rongqiDelete)->where('order_master_id',$id)->update(['isdelete'=>20]);
                if(!$res){
                    throw new \Exception("取消失败1");
                }
            }

            $time = time();
            $price = 0;
            $out_refund_no = createOrdersn($order->user_id,'R');

            $saveOrder = [];
            $orderIds = [];
            foreach ($goodsList as $goods) {
                $item = [
                    'quxiaotime' => $time,
                    'tuikuantime' => $time,
                    'id'=>$goods->order_id
                ];
                if($order->pay_type == 10){
                    // 余额支付
                    $item['status'] = -20;
                }else if($order->pay_type == 20){
                    // 微信支付
                    $order->out_refund_no = $out_refund_no;
                    $item['status'] = -10;
                }else if($order->pay_type == 30){
                    // 线下支付
                    $item['status'] = -20;
                }
                $orderIds[] = $goods->order_id;
                $saveOrder[] = $item;
                $price += $goods->real_price;

                $goods->status = -10;
                $res = $goods->save();
                if (!$res) {
                    throw new \Exception("取消失败2");
                }
            }
            $res = (new \app\api\model\order\Order)->saveAll($saveOrder);
            
            if (!$res) {
                throw new \Exception("取消失败3");
            }

            $norefundcount = \app\api\model\order\OrderGoods::where('order_master_id', 'in', $id)->where('status', 10)->count();
            if ($goodsCount == count($goodsList) ||  $norefundcount == 0) {
                // 全部取消
                if($order->pay_type == 10){
                    // 余额支付
                    $order->status = -20;
                    $order->tuikuantime = $time;
                }else if($order->pay_type == 20){
                    // 微信支付
                    $order->out_refund_no = $out_refund_no;
                    $order->status = -10;
                }else if($order->pay_type == 30){
                    // 线下支付
                    $order->status = -20;
                    $order->tuikuantime = $time;
                }
                $order->quxiaotime = $time;
                $order->refund_status = 30;
                $order->refund_price = $order->price;
                $result = $order->save();
                $price = $order->price;
                if (!$result) {
                    throw new \Exception("取消失败4");
                }
            }else{
                $order->refund_status = 20;
                $order->refund_price = $order->refund_price + $price;
                $result = $order->save();
                if (!$result) {
                    throw new \Exception("取消失败5");
                }
            }

            if ($order->pay_type == 10) {
                // 余额退款
                $user = \app\api\model\User::find($order->user_id);
                $user->setUpdateMoneyParams([
                    'memo' => "取消订单{$order->out_trade_no}退回余额",
                    'title' => '订单退款',
                    'datatype' => 30
                ]);
                $user->money = $user->money + $price;
                $result = $user->save();
                if (!$result) {
                    throw new \Exception("取消失败6");
                }
            }else if($order->pay_type == 20){
                // 微信退款
                $request = request();
                $notifyurl =  $request->root(true) . '/api/notifyx/notifyxOrderRefund/paytype/wechat';
                $params = [
                'out_trade_no' => $order['out_trade_no'],
                'out_refund_no' => $out_refund_no,
                'notify_url' => $notifyurl,
                'amount' => [
                        'refund' => $price * 100,
                        'total' => $order->price * 100,
                        'currency' => 'CNY',
                    ],
                ];
                            
                $result = \addons\epay\library\Service::submitRefund($params,'wechat');
                \think\Log::write('退款请求返回：'.json_encode($result));
                // v2 接口
                // if (!($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS')) { 
                //     \think\Log::write('微信退款失败:'.json_encode($result),'error');
                //     throw new \Exception("微信退款失败");
                // }
                if(!isset($result['status'])){
                    \think\Log::write('微信退款失败:'.json_encode($result),'error');
                    throw new \Exception("微信退款失败");
                }
                // v3 接口  SUCCESS: 退款成功 PROCESSING: 退款处理中 ABNORMAL: 退款异常 CLOSED: 退款关闭
                if($result['status'] == 'ABNORMAL' || $result['status'] == 'CLOSED'){
                    \think\Log::write('微信退款失败:'.json_encode($result),'error');
                    throw new \Exception("微信退款失败");
                }
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollback();
            $this->error($e->getMessage());
        }
        $this->success('取消成功');
        
    }
    

    /**
     * 取样
     */
    public function takeSample()
    {
        $id = $this->request->post('id');
        $orderTube = $this->request->post('orderTube/a');
        if (!$id || !$orderTube) {
            $this->error("参数错误");
        }
        $order = OrderMasterModel::find($id);
        if (!$order) {
            $this->error("订单不存在");
        }
        if ($order->sole_id != $this->auth->id) {
            $this->error("没有权限查看此订单");
        }

        if ($order->status != 10) {
            $this->error("订单状态错误");
        }
        $orderTubeList = \app\api\model\order\OrderTube::with(['biaobenRongqi'])->where('isdelete',10)->where('order_master_id','=',$id)->select();
        if (count($orderTubeList) != count($orderTube)) {
            $this->error("取样信息错误");
        }
        $orderTubeModel = new \app\api\model\order\OrderTube();
        foreach ($orderTube as $value) {
            $result = $orderTubeModel->with(['biaobenRongqi'])->find($value['id']);
            if (!$result) {
                $this->error("取样信息不存在");
            }
            if ($result->tube_number != $value['tube_number']) {
                $this->error("{$result->biaoben_rongqi_name}取样编号错误");
            }
        }
        $order->status = 20;
        $order->quyangtime = time();
        $order->save();
        $this->success('取样成功');
    }

    /**
     * 一键取样
     */
    public function takeSampleAll()
    {
        $hospital_id = $this->request->post('hospital_id');
        if (!$hospital_id) {
            $this->error("参数错误");
        }
        
        $orderList = OrderMasterModel::where('hospital_id','=',$hospital_id)->where('status','=',10)->where('sole_id','=',$this->auth->id)->select();
        if (count($orderList) == 0) {
            $this->error("暂无待取样订单");
        }

        $res = OrderMasterModel::where('hospital_id','=',$hospital_id)
                        ->where('status','=',10)
                        ->where('sole_id','=',$this->auth->id)
                        ->update(['status' => 20,'quyangtime' => time()]);

        if(!$res){
            $this->error("取样失败");
        }
        $this->success('取样成功');
    }

    /**
     * 送检
     */
    public function sendCheck()
    {
        $id = $this->request->post('id');
        $orderTube = $this->request->post('orderTube/a');
        if (!$id || !$orderTube) {
            $this->error("参数错误");
        }
        $order = OrderMasterModel::with(['ordergoods'])->find($id);
        if (!$order) {
            $this->error("订单不存在");
        }
        if ($order->sole_id != $this->auth->id) {
            $this->error("没有权限查看此订单");
        }
        if ($order->status != 20) {
            $this->error("订单状态错误");
        }
        $orderTubeList = \app\api\model\order\OrderTube::with(['biaobenRongqi'])->where('isdelete',10)->where('order_master_id','=',$id)->select();
        if (count($orderTubeList) != count($orderTube)) {
            $this->error("送检信息错误");
        }
        $orderTubeModel = new \app\api\model\order\OrderTube();
        foreach ($orderTube as $value) {
            $result = $orderTubeModel->with(['biaobenRongqi'])->find($value['id']);
            if (!$result) {
                $this->error("送检信息不存在");
            }
            if ($result->tube_number != $value['tube_number']) {
                $this->error("{$result->biaoben_rongqi_name}取样编号错误");
            }
        }

        
        // Db::startTrans();
        $order->status = 30;
        $order->report_status = 10;
        $order->songjiantime = time();
        $res = $order->save();
        if(!$res){
            // Db::rollback();
            $this->error("送检失败");
        }

        // // 佣金
        // $price = 0;
        // $common_discount = config('site.common_discount') ?? 0;

        // $between = [date('Y-m-01 00:00:00', strtotime('last month')),date('Y-m-t 23:59:59', strtotime('last month'))];
        // $saleRank = \app\api\model\SaleRank::where('user_id',$this->auth->id)->where('date','between',$between)->find();
        // if($saleRank && $saleRank->discount > 0){
        //     $common_discount = $saleRank->discount;
        // }
        // if($common_discount < 0){
        //     $common_discount = 0;
        // }
        // if($common_discount > 100){
        //     $common_discount = 100;
        // }

        // $discount = $common_discount / 100;
        // $commissionRecords = new \app\api\model\CommissionRecords();

        // $price = $order->price * $discount;// * 销售折扣
        // $commissionRecords->save([
        //     'sale_id'=>$order->sole_id,
        //     'hospital_id'=>$order->hospital_id,
        //     'commission_discount'=>$common_discount,
        //     'commission_price'=>round($price < 0.01 ? 0.01 : $price,2),
        //     'order_id'=>$order->id,
        //     'out_trade_no'=>$order->out_trade_no
        // ]);

        // $user = \app\api\model\User::find($order->sole_id);
        // $user->setUpdateMoneyParams([
        //     'memo'=>'订单完成分佣',
        //     'title'=>'订单完成分佣',
        //     'datatype'=>20
        // ]);
        // $user->money = $user->money + round($price < 0.01 ? 0.01 : $price,2);
        // $res = $user->save();
        
        
        
        // Db::commit();

        $this->success('送检成功');
    }


    /**
     * 一键取样
     */
    public function sendCheckAll()
    {
        $hospital_id = $this->request->post('hospital_id');
        if (!$hospital_id) {
            $this->error("参数错误");
        }
        
        $orderList = OrderMasterModel::where('hospital_id','=',$hospital_id)->where('status','=',20)->where('sole_id','=',$this->auth->id)->select();
        if (count($orderList) == 0) {
            $this->error("暂无待送检订单");
        }

        Db::startTrans();
        $res = OrderMasterModel::where('hospital_id','=',$hospital_id)
                        ->where('status','=',20)
                        ->where('sole_id','=',$this->auth->id)
                        ->update(['status' => 30,'songjiantime' => time(),'report_status' => 10]);

        if(!$res){
            Db::rollback();
            $this->error("送检失败");
        }

        // 佣金
        // $total_price = 0;
        // $common_discount = config('site.common_discount') ?? 0;

        // $between = [date('Y-m-01 00:00:00', strtotime('last month')),date('Y-m-t 23:59:59', strtotime('last month'))];
        // $saleRank = \app\api\model\SaleRank::where('user_id',$this->auth->id)->where('date','between',$between)->find();
        // if($saleRank && $saleRank->discount > 0){
        //     $common_discount = $saleRank->discount;
        // }
        // if($common_discount < 0){
        //     $common_discount = 0;
        // }
        // if($common_discount > 100){
        //     $common_discount = 100;
        // }

        // $discount = $common_discount / 100;
        // $commissionRecords = new \app\api\model\CommissionRecords();
        // $saveCommission = [];
        // foreach ($orderList as $order) {
        //     $price = $order->price * $discount;// * 销售折扣
        //     $total_price += $price;
        //     $saveCommission[] = [
        //         'sale_id'=>$order->sole_id,
        //         'hospital_id'=>$order->hospital_id,
        //         'commission_discount'=>$common_discount,
        //         'commission_price'=>round($price < 0.01 ? 0.01 : $price,2),
        //         'order_id'=>$order->id,
        //         'out_trade_no'=>$order->out_trade_no
        //     ];
        // }
        // $res = $commissionRecords->saveAll($saveCommission);
        // if(!$res){
        //     Db::rollback();
        //     $this->error("送检失败");
        // }

        // $user = \app\api\model\User::find($order->sole_id);
        // $user->setUpdateMoneyParams([
        //     'memo'=>'订单完成分佣',
        //     'title'=>'订单完成分佣',
        //     'datatype'=>20
        // ]);
        // $user->money = $user->money + round($total_price < 0.01 ? 0.01 : $total_price,2);
        // $res = $user->save();
        // if(!$res){
        //     Db::rollback();
        //     $this->error("送检失败");
        // }
        Db::commit();

        $this->success('送检成功');
    }

}
